using System.Threading;

namespace CodeConsult.Adafruit.BLE_UART
{
    internal class DataCreditManager
    {
        private readonly ManualResetEvent _creditAvailableResetEvent = new ManualResetEvent(false);

        public int DataCreditTotal { get; private set; }
        public int DataCreditAvailable { get; private set; }

        public DataCreditManager(int dataCreditTotal)
        {
            DataCreditTotal = dataCreditTotal;
        }

        public void ResetCreditAvailable()
        {
            SetCreditAvailable(DataCreditTotal);    
        }

        public void SetCreditAvailable(int credits)
        {
            UpdateCreditAvailable(credits - DataCreditAvailable);
        }

        public void UpdateCreditAvailable(int credits)
        {
            var prevCredits = DataCreditAvailable;
            DataCreditAvailable += credits;
            if (prevCredits <= 0 && DataCreditAvailable > 0)
                _creditAvailableResetEvent.Set();
        }

        public void WaitForCreditAvailable()
        {
            if (DataCreditAvailable <= 0)
                _creditAvailableResetEvent.WaitOne(-1, false);

            _creditAvailableResetEvent.Reset();
        }
    }
}
